package com.haoziqi.chapter_05.Sink;

import com.haoziqi.chapter_07.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;

/**
 * description
 * created by A on 2021/3/11
 */
public class MySqlSink {
    public static void main(String[] args) {
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));


        //1.创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        env.fromCollection(waterSensors)
                .addSink(new MySinkFun());
        //提交任务
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class MySinkFun extends RichSinkFunction<WaterSensor> {
    private PreparedStatement pstmt;
    private Connection conn;

    @Override
    public void open(Configuration parameters) throws Exception {
        conn= DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test","root","123456");
        PreparedStatement pre = conn.prepareStatement("insert into sensor values (?,?,?)");

    }
    @Override
    public void close() throws Exception {
        if (pstmt != null) {
            pstmt.close();
        }
        if (conn != null){
            conn.close();
        }
    }
    @Override
    public void invoke(WaterSensor value, Context context) throws Exception {
        pstmt.setString(1, value.getId());
        pstmt.setLong(2, value.getTs());
        pstmt.setInt(3, value.getVc());
        pstmt.execute();
    }

}
